module.exports = app => {
  const mongoose = require("mongoose")

  // 设置 strictQuery 选项以消除警告
  mongoose.set('strictQuery', false);

  // Build Mongo URI from env with sensible defaults
  const DEFAULT_DB_NAME = 'kangxinyuan';
  const envUri = process.env.MONGODB_URI; // e.g. mongodb://127.0.0.1:27017
  const envDbName = process.env.MONGODB_DBNAME || DEFAULT_DB_NAME;
  const mongoUri = envUri ? `${envUri.replace(/\/$/, '')}/${envDbName}` : `mongodb://127.0.0.1:27017/${envDbName}`;

  mongoose.connect(mongoUri, {
    useNewUrlParser: true,
  }).then(() => {
    console.log(`MongoDB connected: ${mongoUri}`)
  }).catch((err) => {
    console.error('MongoDB connection error:', err)
  })

  // Register all models
  require('require-all')(__dirname + '/../models')

  // Ensure collections are created so they are visible in GUI tools
  mongoose.connection.once('open', async () => {
    try {
      const modelNames = mongoose.modelNames();
      for (const name of modelNames) {
        try {
          await mongoose.model(name).createCollection();
        } catch (e) {
          // Ignore if already exists
          if (!/NamespaceExists/i.test(String(e && e.message))) {
            console.warn(`Failed to create collection for model ${name}:`, e.message || e)
          }
        }
      }
      console.log('MongoDB collections ensured for models:', modelNames.join(', '))
    } catch (e) {
      console.warn('Failed ensuring collections:', e.message || e)
    }
  })
}